import React, { useState, useMemo } from 'react';
// import { connect } from 'umi';
import { Form, Input, Modal, Divider, Button, Spin, message, Radio } from 'antd';
import { QuickForm } from 'vv-frontend-components';
import clone from 'lodash/clone';
import { history } from 'umi';
import { SearchInput } from '@/components/UserForm'; // 模糊查询
// import { getCandidateList } from '@/services/myRecruit/candidate';
import request from '@/utils/request';
import { getEmployeeInfoList } from '@/services/components/userform';

const bthMargin = {
    marginLeft: '8px'
};
const formItemLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 14 }
};
const specialformItemLayout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 12 }
};
const dict = {
    同意: {
        label: '同意意见',
        title: '审批同意',
        placeholder: '同意'
    },
    拒绝: {
        label: '拒绝原因',
        title: '审批拒绝',
        placeholder: '请输入拒绝意见'
    },
    退回: {
        label: '退回原因',
        title: '审批退回',
        placeholder: '请输入退回意见'
    }
};
const returnRule = () => ({
    min: 2,
    max: 200,
    message: '请输入2~200个字符'
});
const returnRule2 = () => ({
    required: true,
    min: 2,
    max: 200,
    message: '请输入2~200个字符'
});
const getActionTypelist = ({ label, placeholder }) => ({
    field: 'message',
    label,
    key: 'message',
    props: {
        ...formItemLayout,
        help: '2 - 200 个字符'
    },
    config: {
        rules: placeholder === '同意' ? [returnRule()] : [returnRule2()]
    },
    component: <Input.TextArea style={{ wordBreak: ' break-all' }} placeholder={placeholder} />
});
const useActionType = (type = '同意') => {
    const [actionType, setActionType] = useState(type);
    const [visible, setVisible] = useState(false);
    const result = useMemo(() => dict[actionType], [actionType]);
    const actionTypeList = useMemo(() => getActionTypelist(result), [actionType]);
    return {
        actionType,
        setActionType,
        actionTypeList,
        titleName: result.title,
        visible,
        setVisible
    };
};
// 待我审批列表的同意操作
const TableAction = Form.create()(props => {
    const { form, formKey = '', postId = '', sysbysomeone = false, setSysbysomeone } = props;
    const {
        // actionType,
        setActionType,
        actionTypeList,
        titleName,
        visible,
        setVisible
    } = useActionType();
    const [loading, setLoading] = useState(false);
    const [specitalVisible, setSpecitalVisible] = useState(false); // 监听总裁审批弹框是否打开
    // const [ceoAssiant, setCeoAssisant] = useState(false); // 是否有存在 CEO助理
    const specitalConfig = [
        {
            field: sysbysomeone ? 'sysApproveByPresidentAssistant' : 'sysApproveByPresident',
            label: sysbysomeone ? '是否需要CEO助理审批' : '是否需要CEO审批',
            key: sysbysomeone ? 'sysApproveByPresidentAssistant' : 'sysApproveByPresident',
            props: {
                ...specialformItemLayout
            },
            component: (
                <Radio.Group>
                    <Radio value>是</Radio>
                    <Radio value={false}>否</Radio>
                </Radio.Group>
            ),
            config: {
                initialValue: false,
                rules: [{ required: true, message: '请设置筛选结果' }]
            }
        },
        {
            field: 'message',
            label: '同意意见',
            key: 'message',
            props: {
                ...specialformItemLayout,
                help: '2 - 200 个字符'
            },
            config: {
                rules: [
                    {
                        min: 2,
                        max: 200,
                        message: '请输入2~200个字符'
                    }
                ]
            },
            component: <Input.TextArea style={{ wordBreak: ' break-all' }} placeholder="同意" />
        }
    ];
    const handleOk = () => {
        form.validateFields(async (err, values) => {
            if (err) return;
            setLoading(true);
            const obj = clone(values);
            if (
                !obj.message ||
                obj.message === 'undefined' // ？？？
            ) {
                obj.message = '';
            }
            await props.actionSubmit(obj, titleName, props.extradata);
            setLoading(false);
            // if (isOk) {
            setVisible(false);
            setSpecitalVisible(false);
            form.resetFields();
            // }
            // do somesth of netWork err
        });
    };

    return (
        <>
            <span>
                {formKey === 'websiteNews' && (postId === 251 || ([148, 173].includes(postId) && sysbysomeone)) ? (
                    <a
                        href="#"
                        onClick={() => {
                            if (postId === 148 || postId === 173) {
                                setSysbysomeone(true);
                            }
                            setSpecitalVisible(true);
                        }}
                    >
                        同意
                    </a>
                ) : (
                    <a
                        href="#"
                        onClick={() => {
                            setVisible(true);
                            setActionType('同意');
                        }}
                    >
                        同意
                    </a>
                )}

                <Divider type="vertical" />
                <a
                    href="#"
                    onClick={() => {
                        setVisible(true);
                        setActionType('拒绝');
                    }}
                >
                    拒绝
                </a>
                <Divider type="vertical" />
                <a
                    href="#"
                    onClick={() => {
                        setVisible(true);
                        setActionType('退回');
                    }}
                >
                    退回
                </a>
            </span>

            <Modal
                title={titleName}
                visible={visible}
                confirmLoading={loading}
                onOk={() => {
                    handleOk();
                }}
                onCancel={() => {
                    form.resetFields();
                    setVisible(false);
                }}
            >
                <Spin spinning={loading}>
                    <Form layout="horizontal">
                        <QuickForm config={[actionTypeList]} form={form} />
                    </Form>
                </Spin>
            </Modal>
            <Modal
                title="审批同意"
                visible={specitalVisible}
                confirmLoading={loading}
                onOk={() => {
                    handleOk();
                }}
                onCancel={() => {
                    setSpecitalVisible(false);
                    form.resetFields();
                }}
            >
                <Form layout="horizontal">
                    <QuickForm config={specitalConfig} form={form} />
                </Form>
            </Modal>
        </>
    );
});
TableAction.displayName = 'TableAction';

// 待我审批列表详情的同意操作
const DetailAction = Form.create()(props => {
    const { form, dataSource = {}, postId = '' } = props;
    const {
        // actionType,
        setActionType,
        actionTypeList,
        titleName,
        visible,
        setVisible
    } = useActionType();
    // 获取登陆人公司id
    const user = localStorage.getItem('user');
    // const { companyId = '', id = '' } = user ? JSON.parse(user) : {};
    const { id = '' } = user ? JSON.parse(user) : {};
    const [datailloading, setDetailLoading] = useState(false);
    const [appoint, setAppoint] = useState(false); // 监听指派弹框是否打开
    const [specitalVisible, setSpecitalVisible] = useState(false); // 监听总裁审批弹框是否打开
    const [sysbysomeone, setSysbysomeone] = useState(false); // 是否需要ceo助理审批
    // const [ceoAssiant, setCeoAssisant] = useState(false); // 是否有存在 CEO助理
    const appintConfig = [
        {
            field: 'appintobject',
            label: '指派对象',
            key: 'appintobject',
            props: {
                ...formItemLayout
            },
            config: {
                rules: [{ required: true, message: '请选择指派对象' }]
            },
            component: (
                <SearchInput
                    params={{
                        companyId: 100,
                        id
                    }}
                    requireParam={[]}
                    getData={params =>
                        getEmployeeInfoList(params).then(res => {
                            if (res && res.code === 10000) {
                                return res.data.map(item => ({ ...item, userCode: item.employeeCode })) || [];
                            }
                            return [];
                        })
                    }
                    selectProps={{
                        placeholder: '请选择指派对象',
                        style: { minWidth: 200 },
                        allowClear: true
                    }}
                    fieldsName={{
                        value: 'userCode',
                        title: 'employeeName',
                        extraParams: 'userName',
                        appoint: true
                    }}
                    // onChange={this.handleSelect}
                />
            )
        }
    ];
    const specitalConfig = [
        {
            field: sysbysomeone ? 'sysApproveByPresidentAssistant' : 'sysApproveByPresident',
            label: sysbysomeone ? '是否需要CEO助理审批' : '是否需要CEO审批',
            key: sysbysomeone ? 'sysApproveByPresidentAssistant' : 'sysApproveByPresident',
            props: {
                ...specialformItemLayout
            },
            component: (
                <Radio.Group>
                    <Radio value>是</Radio>
                    <Radio value={false}>否</Radio>
                </Radio.Group>
            ),
            config: {
                initialValue: false,
                rules: [{ required: true, message: '请设置筛选结果' }]
            }
        },
        {
            field: 'message',
            label: '同意意见',
            key: 'message',
            props: {
                ...specialformItemLayout,
                help: '2 - 200 个字符'
            },
            config: {
                rules: [
                    {
                        min: 2,
                        max: 200,
                        message: '请输入2~200个字符'
                    }
                ]
            },
            component: <Input.TextArea style={{ wordBreak: ' break-all' }} placeholder="同意" />
        }
    ];
    const handleAppoint = () => {
        form.validateFields(async (err, values) => {
            if (!err) {
                // 补充modal的confirmLoading属性
                setDetailLoading(true);
                const newValue = values.appintobject.split('#');
                const response = await request('/api/oa/v1/workflow/myprocess/assignapprovaltask', {
                    method: 'POST',
                    data: {
                        applyId: dataSource.id ? dataSource.id : '',
                        processInstanceId: dataSource.processInstanceId ? dataSource.processInstanceId : '',
                        assigne: newValue[0],
                        assigneName: newValue[1]
                    }
                });
                if (response.code === 10000) {
                    message.success('操作成功！');
                    form.resetFields();
                    history.push('/personal/portal/flow/mine/myAudited');
                } else {
                    message.error(response.msg);
                    form.resetFields();
                }
                // 关闭模态框
                setAppoint(false);
                setDetailLoading(false);
            }
        });
    };
    const handleOk = () => {
        form.validateFields(async (err, values) => {
            if (err) return;
            setDetailLoading(true);
            const obj = clone(values);
            if (!obj.message || obj.message === 'undefined') {
                obj.message = '';
            }
            const isOk = await props.actionSubmit(obj, titleName, props.extradata);
            setDetailLoading(false);
            if (isOk) {
                setVisible(false);
                setSpecitalVisible(false);
                form.resetFields();
            }
            // do somesth of netWork err
        });
    };
    const btn1 = () => (
        <Button
            type="primary"
            style={bthMargin}
            onClick={() => {
                if (postId === 148 || postId === 173) {
                    setSysbysomeone(true);
                }
                setSpecitalVisible(true);
            }}
        >
            同意
        </Button>
    );
    const btn2 = () => (
        <Button
            type="primary"
            key="1"
            style={bthMargin}
            onClick={() => {
                setVisible(true);
                setActionType('同意');
            }}
        >
            同意
        </Button>
    );

    React.useEffect(() => {
        const fetchCeoAssistant = async () => {
            if ([148, 173].includes(postId)) {
                // 请求是否有ceo助理
                const response = await request('/api/oa/v1/post/getemployeebypostidbyprocess/251');
                if (response.code === 10000) {
                    setSysbysomeone(true);
                } else {
                    setSysbysomeone(false);
                    form.setFieldsValue({
                        sysApproveByPresidentAssistant: false
                    });
                }
            }
        };
        fetchCeoAssistant();
    }, []);

    return (
        <>
            <Button
                key="4"
                style={{ marginRight: '8px' }}
                onClick={() => {
                    setAppoint(true);
                }}
            >
                指派
            </Button>
            <Button
                key="3"
                onClick={() => {
                    setVisible(true);
                    setActionType('退回');
                }}
            >
                退回
            </Button>
            <Button
                key="2"
                style={bthMargin}
                onClick={() => {
                    setVisible(true);
                    setActionType('拒绝');
                }}
            >
                拒绝
            </Button>
            {dataSource.formKey === 'websiteNews' && (postId === 251 || ([148, 173].includes(postId) && sysbysomeone))
                ? btn1()
                : btn2()}

            <Modal
                title={titleName}
                visible={visible}
                confirmLoading={datailloading}
                onOk={() => {
                    handleOk();
                }}
                onCancel={() => {
                    form.resetFields();
                    setVisible(false);
                }}
            >
                <Form layout="horizontal">{visible && <QuickForm config={[actionTypeList]} form={form} />}</Form>
            </Modal>
            <Modal
                title="流程指派"
                visible={appoint}
                confirmLoading={datailloading}
                onOk={() => {
                    handleAppoint();
                }}
                onCancel={() => {
                    form.resetFields();
                    setAppoint(false);
                }}
            >
                <Form layout="horizontal">{appoint && <QuickForm config={appintConfig} form={form} />}</Form>
            </Modal>
            <Modal
                title="审批同意"
                visible={specitalVisible}
                confirmLoading={datailloading}
                onOk={() => {
                    handleOk();
                }}
                onCancel={() => {
                    setSpecitalVisible(false);
                    form.resetFields();
                }}
            >
                <Form layout="horizontal">{specitalVisible && <QuickForm config={specitalConfig} form={form} />}</Form>
            </Modal>
        </>
    );
});
DetailAction.displayName = 'DetailAction';

export { TableAction, DetailAction };
